package com.example.demo.controller;


import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Map;

////定义好访问地址
//@Controller
//public class LoginController {
//    @RequestMapping("/login_input")
//    public String login_input(){
//        return "login";
//    }
//    @RequestMapping("/login")//向页面传值 Model
//    public String login(String username, String password, Model model, HttpSession session){
//        if(username.equals("admin") && password.equals("123")){//判断
//            model.addAttribute("username",username);
//            session.setAttribute("login_user",username);
//            return "login_suc";
//        }else{
//            return "redirect:login_fail";  // 重定向失败页面
//        }
//    }
//}

//定义好访问地址
@Controller
public class LoginController {
    @RequestMapping("/login_input")
    public String login_input(){
        return "login";
    }
    @RequestMapping("/login")//向页面传值 Model
    public String login(String username, String password, Model model, HttpSession session){
        if(username.equals("admin") && password.equals("123")){//判断
            model.addAttribute("username",username);
            session.setAttribute("login_user",username);
            return "login_suc";
        }else{
            return "redirect:login_fail";  // 重定向失败页面
        }
    }

    @Autowired
    UserService service;
    @RequestMapping("/loginDb")
    public String loginDb(User user, Model model, HttpSession session, RedirectAttributes redirectAttributes){
        boolean isSuc=service.login(user);
        if(isSuc){
            model.addAttribute("username",user.getUsername());
            session.setAttribute("login_user",user.getUsername());
            return "login_suc";//默认forward
        }else{//登陆失败，重定向
            //重定向的时候看不到原来的参数
            model.addAttribute("username","重定向看不到原来的值");
            redirectAttributes.addAttribute("redirect_msg","重定向传值");
            //只显示一次，第二次不见
            redirectAttributes.addFlashAttribute("flash_msg","只显示一次，刷新不见");
            return "redirect:login_fail";//重定向只能指向action
        }
    }

    @RequestMapping("login_fail")
    public String login_fail(){
        return "login_fail";
    }

    @ResponseBody
    @RequestMapping("/login_async")
    public Map loginAsync(@RequestBody User user){
        boolean isSuc=service.login(user);
        if(isSuc){
            return Map.of("code",0,"msg","");
        }else{
            return Map.of("code",1,"msg","用户名或密码错误");
        }
    }

}

